//
//  NewsViewController.m
//  myCar
//
//  Created by 王子洁 on 14/10/28.
//  Copyright (c) 2014年 lanou3g.com 蓝鸥科技. All rights reserved.
//

#import "NewsViewController.h"
#import "MJRefresh.h"
#import "NewsTableViewCell.h"
#import "Information.h"
#import "UIImageView+WebCache.h"
#import "WebViewController.h"
#import "MarketView.h"
#import "CityViewController.h"
#import "CityName.h"
#import "WebColor.h"
#import "AFNetworking.h"

#import "LXAppDelegate.h"

@interface NewsViewController ()<UITableViewDataSource, UITableViewDelegate, CityViewControllerDelegate>

@property (nonatomic, retain)UITableView *tableView;

@property (nonatomic, retain)NSMutableArray *infoArr;

@property (nonatomic, retain)UIScrollView *scrollView;

@property (nonatomic, assign)int countx;

@property (nonatomic, retain)CityName *city;

@property (nonatomic, retain)MarketView *marketView;


@end

@implementation NewsViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
        self.infoArr = [NSMutableArray array];
        self.city = [[CityName alloc] init];
        self.countx = 1;
    }
    return self;
}

- (void)setButtonTitle:(NSString *)buttonTitle
{
    if (_buttonTitle != buttonTitle) {
        [_buttonTitle release];
        _buttonTitle = [buttonTitle retain];
    }
    self.city.city = _buttonTitle;
    
}

- (void)dealloc
{
    [_infoArr release];
    [_city release];
    [_tableView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    //self.title = self.info.title;
    
    self.navigationController.navigationBar.tintColor = [WebColor white];
    self.navigationItem.leftBarButtonItem.title = self.info.title;
       self.view.backgroundColor = [UIColor darkGrayColor];
    
   
    [self initView];
    [self reloadData];
    [self setupRefresh];
    
    
    NSLog(@"self.city %@", self.city.city);
}

- (void)reloadData
{
//    UIWindow *window = [(LXAppDelegate *)[[UIApplication sharedApplication] delegate] window];
    
    if ([self.info.title isEqualToString:@"行情"]) {
        //@"http://mrobot.pcauto.com.cn/v2/cms/channels/55555?pageNo=%d&pageSize=20&pro=%@&city=%@&v=4.0.0
        NSString *str = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v2/cms/channels/55555"];
        if (self.proName == nil) {
            self.proName = @"辽宁";
            self.buttonTitle = @"大连";
        }
        
        NSDictionary *dic = @{@"pageNo": [NSNumber numberWithInt:self.countx],@"pageSize":@"20",@"pro":self.proName,@"city":self.buttonTitle,@"v":@"4.0.0"};
            AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
            [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
           [manager1 GET:str parameters:dic success:^(AFHTTPRequestOperation *operation, id responseObject) {
               NSArray *data = [responseObject valueForKey:@"data"];
               for (NSDictionary *dic in data) {
                   Information *info = [[Information alloc] init];
                   info.image = [dic valueForKey:@"image"];
                   info.title = [dic valueForKey:@"title"];
                   NSString *str = [[dic valueForKey:@"count"] description];
                   info.count = [NSString stringWithFormat:@"%@评论", str];
                   if ([info.count isEqualToString:@"0评论"]) {
                       info.count = @"抢沙发";
                   }
                   info.date = [dic valueForKey:@"pubDate"];
                   info.url = [dic valueForKey:@"url"];
                   [self.infoArr addObject:info];
                   [info release];
               }
               [self.tableView reloadData];

               self.tableView.frame = CGRectMake(0, 50, self.view.bounds.size.width, 100 * self.infoArr.count);
               self.scrollView.contentSize = CGSizeMake(0, 100 * self.infoArr.count + 50);

            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"网络错误");
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起暂无网络" message:@"请返回" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"确定", nil];
                [alertView show];
                [alertView release];
                UIImageView *imageView = [[UIImageView alloc] init];
                imageView.image = [UIImage imageNamed:@"noNet.jpg"];
                self.tableView.backgroundView = imageView;
                [imageView release];
            }];
    } else {
                NSString *str = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v2/cms/channels/%@?pageNo=%d&pageSize=20&v=4.0.0", self.info.number, self.countx];
        
            AFHTTPRequestOperationManager *manager1 = [AFHTTPRequestOperationManager manager];
        
            [manager1.responseSerializer setAcceptableContentTypes: [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css", nil]];
           [manager1 GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
               NSArray *data = [responseObject valueForKey:@"data"];
               for (NSDictionary *dic in data) {
                   Information *info = [[Information alloc] init];
                   info.image = [dic valueForKey:@"image"];
                   info.title = [dic valueForKey:@"title"];
                   NSString *str = [[dic valueForKey:@"count"] description];
                   info.count = [NSString stringWithFormat:@"%@评论", str];
                   if ([info.count isEqualToString:@"0评论"]) {
                       info.count = @"抢沙发";
                   }
                   info.date = [dic valueForKey:@"pubDate"];
                   info.url = [dic valueForKey:@"url"];
                   [self.infoArr addObject:info];
                   [info release];
                   
               }
               [self.tableView reloadData];
            } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                NSLog(@"网络错误");
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(50, 120, 280, 100)];
                imageView.image = [UIImage imageNamed:@"poNet.jpg"];
                self.tableView.backgroundView = imageView;
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"对不起暂无网络" message:@"请返回" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:@"确定", nil];
                [imageView release];
                [alertView show];
                [alertView release];
            }];
    }
}


-(void)initView
{
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 64) style:UITableViewStylePlain];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    if ([self.info.title isEqualToString:@"行情"]) {
        self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - 64)];
        
        if ([self.info.title isEqualToString:@"行情"]) {
            self.infoArr = [NSMutableArray array];
            
        self.scrollView.backgroundColor = [UIColor whiteColor];
        [self.view addSubview:self.scrollView];
        
       self.marketView = [[MarketView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 50)];
            [self.marketView.myButton setTitle:self.buttonTitle forState:(UIControlStateNormal)];
        }

        self.marketView.backgroundColor = [WebColor whiteSmoke];
        self.tableView.frame = CGRectMake(0, 50, self.view.bounds.size.width, self.view.bounds.size.height - 64);
        self.tableView.scrollEnabled = NO;
        [self.marketView.myButton addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
        
        [self.scrollView addSubview:self.marketView];
        [self.scrollView addSubview:self.tableView];

        [_marketView release];
        [_scrollView release];
    } else {
        [self.view addSubview:self.tableView];
    }
    [_tableView release];

}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.infoArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *str = @"reuse";
    NewsTableViewCell *cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:str];
    cell.backgroundColor = [WebColor lime];
    if (cell == nil) {
        cell = [[[NewsTableViewCell alloc] init]autorelease];
    }
    Information *info = [self.infoArr objectAtIndex:indexPath.row];
    cell.info = info;
    
    NSString *strInfo = [NSString string];
    if (info.image.length != 0) {
        strInfo = [info.image substringFromIndex:info.image.length - 1];
    }
    
    if ([strInfo isEqualToString:@"g"]) {
        [cell.newsImageView setImageWithURL:[NSURL URLWithString:info.image]];
    } else {
        cell.newsImageView.image = [UIImage imageNamed:@"noPic.jpg"];
    }
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, 80)];
    imageView.image = [UIImage imageNamed:@"cellBcg100.jpg"];
    cell.backgroundView = imageView;
    [imageView release];
   
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WebViewController *webVC = [[WebViewController alloc] init];
    Information *info = [self.infoArr objectAtIndex:indexPath.row];
    webVC.info = info;
    [self.navigationController pushViewController:webVC animated:YES];
    [webVC release];
}

- (void)buttonClicked:(UIButton *)button
{
    CityViewController *cityVC = [[CityViewController alloc] init];
    cityVC.delegate = self;
    [self.navigationController pushViewController:cityVC animated:YES];
}

- (void)passValue:(CityName *)cityName
{
    [self.marketView.myButton setTitle:cityName.city forState:UIControlStateNormal];
    self.proName = cityName.pro;
    self.city = cityName;
    
    if (self.buttonTitle != cityName.city) {
        self.infoArr = [NSMutableArray array];
        self.buttonTitle = cityName.city;
        self.proName = cityName.pro;
        NSLog(@"%@,.....%@", cityName.city, cityName.pro);
        [self reloadData];
        [self headerRereshing];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navbackground.jpg"] forBarMetrics:UIBarMetricsDefault];
}



- (void)buttonClicked1:(UIButton *)button
{
    NSLog(@"dianji");
}

#pragma mark 刷新方法
- (void)setupRefresh
{
    if ([self.info.title isEqualToString:@"行情"]) {
        
        // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
        [self.scrollView addHeaderWithTarget:self action:@selector(headerRereshing)];
        [self.scrollView headerBeginRefreshing];
        
        // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
        [self.scrollView addFooterWithTarget:self action:@selector(footerRereshing)];
        [self.scrollView footerEndRefreshing];
        //
        // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
        self.scrollView.headerPullToRefreshText = @"下拉以上弦...";
        self.scrollView.headerReleaseToRefreshText = @"松开即可上弦...";
        self.scrollView.headerRefreshingText = @"上弦中...";
        
        self.scrollView.footerPullToRefreshText = @"上拉可以加载更多数据了";
        self.scrollView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
        self.scrollView.footerRefreshingText = @"加载中";
        
        self.countx = 2;

    } else {
    
        // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
        [self.tableView addHeaderWithTarget:self action:@selector(headerRereshing)];
        [self.tableView headerBeginRefreshing];
        
        // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
        [self.tableView addFooterWithTarget:self action:@selector(footerRereshing)];
        [self.tableView footerEndRefreshing];
        //
        // 设置文字(也可以不设置,默认的文字在MJRefreshConst中修改)
        self.tableView.headerPullToRefreshText = @"下拉以上弦...";
        self.tableView.headerReleaseToRefreshText = @"松开即可上弦...";
        self.tableView.headerRefreshingText = @"上弦中...";
        
        self.tableView.footerPullToRefreshText = @"上拉可以加载更多数据了";
        self.tableView.footerReleaseToRefreshText = @"松开马上加载更多数据了";
        self.tableView.footerRefreshingText = @"加载中";
        
        self.countx = 2;
    }
}
#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
//
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
    if ([self.info.title isEqualToString:@"行情"]) {
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            self.scrollView.contentSize = CGSizeMake(0, 100 * self.infoArr.count + 50);
            [self.scrollView headerEndRefreshing];

    } else {
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView headerEndRefreshing];
    }
         });
}

- (void)footerRereshing
{
    //_dataSource = [[NSMutableArray alloc]init];
    
    self.countx += 1;
    
    
    // 2.2秒后刷新表格UI
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self reloadData];
        //[self.tableView reloadData];
        if ([self.info.title isEqualToString:@"行情"]) {
            self.tableView.frame = CGRectMake(0, 50, self.view.bounds.size.width, 100 * self.infoArr.count);
            self.scrollView.contentSize = CGSizeMake(0, 100 * self.infoArr.count + 50);
            [self.scrollView headerEndRefreshing];
            [self.scrollView footerEndRefreshing];
            
        } else {
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [self.tableView footerEndRefreshing];
        }
        _countx += 1;
    });
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
